package com.czy.owner.ui.business;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.czy.owner.R;
import com.czy.owner.adapter.BaseRecyclerAdapter;
import com.czy.owner.adapter.BusinessAdapter;
import com.czy.owner.adapter.BusinessCateSelectAdapter;
import com.czy.owner.callback.RecycleViewDivider;
import com.czy.owner.db.UserHelper;
import com.czy.owner.entity.BusinessCategoryModel;
import com.czy.owner.entity.BusinessServiceModel;
import com.czy.owner.entity.WebViewRequestParam;
import com.czy.owner.global.Constants;
import com.czy.owner.ui.BaseFragment;
import com.czy.owner.ui.order.ProjectDetailsWebviewActivity;
import com.czy.owner.utils.MyLog;
import com.czy.owner.utils.PhoneUtils;
import com.czy.owner.utils.SharedPreferencesUtils;
import com.easyrecycleview.EasyRecyclerView;
import com.easyrecycleview.adapter.RecyclerArrayAdapter;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

import static com.czy.owner.entity.WebViewRequestParam.REQUEST_POST;

/**
 * @author: Raven
 * @date: 2017/12/14 20:06
 * @email: xiexiaomeng_001@163.com
 * @description: 业务分类列表页面
 */

public class BusinessBaseFragment extends BaseFragment implements RecyclerArrayAdapter.OnLoadMoreListener,SwipeRefreshLayout.OnRefreshListener{

    private static final String TAG = "BusinessBaseFragment";
    @BindView(R.id.rv_child_cate)
    RecyclerView rvChildCate;
    @BindView(R.id.rv_content)
    EasyRecyclerView rvContent;
    private Handler handler = new Handler();

    /**
     * 头部子分类Adapter
     */
    private BusinessCateSelectAdapter mCateSelectAdapter;

    /**
     * 服务列表Adapter
     */
    private BusinessAdapter mBusinessAdapter;

    /**
     * 当前分类的数据模型，含Id 和子分类List
     */
    private BusinessCategoryModel cateModel;
    private int page = 1;
    private int storeServiceId = 0;

    @Override
    protected int attachLayoutRes() {
        return R.layout.fragment_business_base;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {
        Bundle bundle = getArguments();
        if(bundle != null){
            //从Activity中获取到分类的数据模型
           cateModel = (BusinessCategoryModel) bundle.getSerializable("cate_model");
           MyLog.d(TAG,""+cateModel.getServiceName());
           MyLog.d(TAG,""+cateModel.getStoreServiceId());
        }

        /**
         * 页面初始化
         */
        if(cateModel.getSubs()!=null && cateModel.getSubs().size() > 0){
            //分类的子分类不为空，则显示头部View
            rvChildCate.setVisibility(View.VISIBLE);
            //顶部分类的RecyclerView
            rvChildCate.setLayoutManager(new GridLayoutManager(getActivity() ,4));
            mCateSelectAdapter = new BusinessCateSelectAdapter(getActivity() , cateModel.getSubs());
            mCateSelectAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(int position, Object o, View view) {
                    if(mCateSelectAdapter.getSelectedPosition() != position ) {
                        mCateSelectAdapter.setSelectedPosition(position);
                        storeServiceId = cateModel.getSubs().get(position).getStoreServiceId();
                    }else{
                        mCateSelectAdapter.setSelectedPosition(-1);
                        storeServiceId = cateModel.getStoreServiceId();
                    }
                    page = 1;
                    getServiceList(true);

                }
            });
            rvChildCate.setAdapter(mCateSelectAdapter);
            //默认加载主分类列表项
            storeServiceId = cateModel.getStoreServiceId();
            getServiceList(true);
        }else {
            //子分类为空，不显示顶部View
            storeServiceId = cateModel.getStoreServiceId();
            rvChildCate.setVisibility(View.GONE);
            getServiceList(true);
        }


        /**
         * 服务列表页面
         */
        rvContent.setLayoutManager(new LinearLayoutManager(getActivity()));
        rvContent.addItemDecoration(new RecycleViewDivider(getActivity(), LinearLayoutManager.VERTICAL,
                R.drawable.shape_shopping_strategy_divider_decoration));
        mBusinessAdapter = new BusinessAdapter(getActivity());
        rvContent.setAdapterWithProgress(mBusinessAdapter);
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.order_empty_view, (ViewGroup) getActivity().getWindow().getDecorView(), false);
        TextView tv_content = (TextView) view.findViewById(R.id.tv_content);
        tv_content.setText("没有服务项");
        rvContent.setEmptyView(view);
        mBusinessAdapter.setMore(R.layout.view_more,this);
        mBusinessAdapter.setNoMore(R.layout.view_nomore_new, new RecyclerArrayAdapter.OnNoMoreListener() {
            @Override
            public void onNoMoreShow() {
            }

            @Override
            public void onNoMoreClick() {
                mBusinessAdapter.resumeMore();
            }
        });
        mBusinessAdapter.setError(R.layout.view_error_net, new RecyclerArrayAdapter.OnErrorListener() {
            @Override
            public void onErrorShow() {
                mBusinessAdapter.resumeMore();
            }

            @Override
            public void onErrorClick() {
                mBusinessAdapter.resumeMore();

            }
        });
        rvContent.setRefreshListener(this);

        mBusinessAdapter.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position, Object o) {
                int storeServiceId = mBusinessAdapter.getAllData().get(position).getStoreServiceId();
                setIntentDetails(""+storeServiceId);
            }
        });
    }

    @Override
    protected void updateViews() {

    }


    /**
     * 跳转到对应服务Id的详情Web页面
     * @param storeServiceId
     */
    public void setIntentDetails(String storeServiceId) {
        WebViewRequestParam webViewRequestParam = new WebViewRequestParam(Constants.APP_API_BASE + "/own/order/serviceInfo");
        webViewRequestParam.setRequestMethod(REQUEST_POST);
        webViewRequestParam.setParams("session=" + UserHelper.getInstance().getSessionInfoModel(
                getContext()).getSession() + "&storeId=" + (SharedPreferencesUtils.getParam(getActivity(), UserHelper.getInstance().getUserAccount() + Constants.SHARED_PREFERENCES_KEY_BINDSTOREID, 0) + "") + "&storeServiceId="
                + storeServiceId);
        webViewRequestParam.setTitle("服务详情");
        Intent intent = new Intent(getContext(), ProjectDetailsWebviewActivity.class);
        intent.putExtra(Constants.TRANSMISSION_CONTENT_KEY, webViewRequestParam);
        startActivity(intent);
    }

    /**
     * 获取服务列表数据
     * @param isFirstData
     */
    private void getServiceList(final boolean isFirstData){

        RequestParams params = new RequestParams(Constants.APP_API_BASE + Constants.SERVICE_LIST);
        params.addBodyParameter("session", UserHelper.getInstance().getSession(getContext()));
        params.addBodyParameter("storeId", ""+cateModel.getStoreId());
        params.addBodyParameter("page", page + "");
        params.addBodyParameter("size", "10");
        if(storeServiceId > 0) {
            params.addBodyParameter("storeServiceId", "" + storeServiceId);
        }
//        params.addBodyParameter("serviceName", ""+serviceName);

        MyLog.d(TAG,"params = " + params.toString());
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                MyLog.e(TAG,"result = " + result);
                String data = PhoneUtils.checkResponseFlag(getActivity(),result);
                if(data!=null){

                    try {
                        Gson gson = new GsonBuilder().create();
                        BusinessServiceModel model  = gson.fromJson(data,BusinessServiceModel.class);
                        if (isFirstData) {
                            mBusinessAdapter.clear();
                        }
                        if (model.getList().size() < 9) {
                            mBusinessAdapter.stopMore();
                        }
                        mBusinessAdapter.addAll(model.getList());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                MyLog.e("RAVEN","error = " + ex.getMessage());
                mBusinessAdapter.clear();
                mBusinessAdapter.resumeMore();
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
            }
        });
    }

    @Override
    public void onRefresh() {
        MyLog.d("RAVEN","=====onRefresh======");
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                //刷新
                page = 1;
                getServiceList(true);
            }
        }, 1000);
    }

    @Override
    public void onLoadMore() {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                //刷新
                if (!PhoneUtils.isNetworkConnected(getActivity())) {
                    mBusinessAdapter.pauseMore();
                    rvContent.showError();
                    return;
                }
                page++;
                getServiceList(false);
            }
        }, 1000);
    }
}
